package cn.teleware.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author: 洪少尉
 * @Date: 2020/11/13 21:13
 * @Description:
 */
@RequestMapping("receive")
@RestController
public class ReceiveController {

	@PostMapping
	public String receive(@RequestParam("multipartFile") MultipartFile file) throws IOException {
		return save(file, "C:\\Users\\Administrator\\Desktop", "新文件");
	}

	/**
	 * @param file     上传的文件
	 * @param dirName  需要保存在本地的路径
	 * @param fileName 重命名(不需要文件后缀)
	 * @return java.lang.String
	 * @author 洪少尉
	 * @date 2020/11/13 22:26
	 **/
	private String save(MultipartFile file, String dirName, String fileName) throws IOException {
		String originalFilename = file.getOriginalFilename();
		if (originalFilename != null) {
			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(dirName + File.separator + fileName + suffix));
			return dirName + File.separator + fileName + suffix;
		}
		return "";
	}
}
